package fanshe.first.demo03;

import java.lang.reflect.Field;

/**
 * @author Mr.ma
 * @since 2022/10/27 15:44
 * 通过反射获取类中的属性，方法有：
 *      1、getField()
 *      2、getFields()
 *      3、getDeclaredField()
 *      4、getDeclaredFields()
 * 上述方法前两个则是可以获取反射类自身及父类中的公开方法，后两个只能获取反射类自身的方法
 **/
public class Test03 {
    public static void main(String[] args) throws Exception {
        Animal dog = new Dog();
        //doSome(dog);
        doOther(dog);
    }
    public static void doSome(Animal animal) throws Exception{
        Class<? extends Animal> dogClass = animal.getClass();
        Field[] fields = dogClass.getFields();
        for (Field field : fields) {
            System.out.println("field = " + field.getName());
        }
        Field name = dogClass.getField("name");
        System.out.println("name = " + name.getName());
        Field[] declaredFields = dogClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println("declaredField = " + declaredField.getName());
        }
        Field master = dogClass.getDeclaredField("master");
        System.out.println("master = " + master.getName());
    }
    public static void doOther(Animal animal) throws Exception {
        Class<? extends Animal> aClass = animal.getClass();
        Animal animal1 = aClass.newInstance();
        Field[] fields = aClass.getFields();
        for (Field field : fields) {
            field.set(animal,"sss");
        }
        System.out.println("animal = " + animal);
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            declaredField.set(animal1,"lll");
            System.out.println(declaredField.getName() + "=========" + declaredField.get(animal1));
        }
        System.out.println("animal1 = " + animal1);
    }
}
class Animal {
    public String color;
    private int age;
}
class Dog extends Animal{
    public String name;
    private String master;

    @Override
    public String toString() {
        return "Dog{" +
                "color='" + color + '\'' +
                ", name='" + name + '\'' +
                ", master='" + master + '\'' +
                '}';
    }
}